package com.hty.locusmap;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import android.app.Activity;
import android.app.Notification;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;

public class CurrentLocus extends Activity {
	MapView mMapView = null;
	BaiduMap mBaiduMap;
	LocationClient mLocationClient;

	boolean isFirstLoc = true;
	BitmapDescriptor mCurrentMarker;
	LocationMode locationMode;
	TextView tv1, tv2;
	LatLng p1, p2;
	double lc = 0, speed, alt, speedmax = 0, ltt, lgt, ltt1, lgt1, distance, distancesend = 0;
	Date date, time_start;
	long duration;
	SimpleDateFormat timeformat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
	SimpleDateFormat timeformatd = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
	SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
	SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
	SimpleDateFormat dateformat2 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
	int ER, lci;
	Button button_location_mode;
	SharedPreferences sharedPreferences;
	String c, upload_server = "", filename = "";
	Notification mNotification;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.activity_current);
		MainApplication.getInstance().addActivity(this);
		MainApplication.mContext = this;
		MainApplication.mode = "map";
		timeformat.setTimeZone(TimeZone.getDefault());
		timeformatd.setTimeZone(TimeZone.getTimeZone("GMT+0"));
		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		upload_server = sharedPreferences.getString("uploadServer", "http://sonichy.gearhostpreview.com/locusmap");
		tv1 = (TextView) findViewById(R.id.textView_info);
		tv2 = (TextView) findViewById(R.id.textView_copyright);
		mCurrentMarker = null;
        locationMode = LocationMode.NORMAL;
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();
		mBaiduMap.setMyLocationEnabled(true);
		mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(locationMode, true, mCurrentMarker));
		UiSettings settings = mBaiduMap.getUiSettings();
		settings.setRotateGesturesEnabled(false);
		settings.setOverlookingGesturesEnabled(false);

        button_location_mode = (Button) findViewById(R.id.button_map);
        button_location_mode.setOnClickListener(onClickListener);

		MyLocationListenner myLocationListener = new MyLocationListenner();
		mLocationClient = new LocationClient(this);
		mLocationClient.registerLocationListener(myLocationListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		//option.setCoorType("gcj02"); // 默认
		option.setScanSpan(5000);	//定位请求时间间隔
		mLocationClient.setLocOption(option);
		initNotification();
		mLocationClient.enableLocInForeground(1, mNotification);
		mLocationClient.start();
		date = new Date();
		time_start = date;
		ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton_location);
		imageButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(new LatLng(ltt, lgt)));
			}
		});
		//filename = dateformat1.format(time_start) + "BD.gpx";
		filename = dateformat1.format(time_start) + ".gpx";
		RWXML.create(dateformat1.format(time_start));
	}

	@Override
	protected void onDestroy() {
		mLocationClient.stop();
		mMapView.onDestroy();
		mMapView = null;
		//mLocationClient.disableLocInForeground(true);
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
        SDKInitializer.setCoordType(CoordType.GCJ02); //百度地图SDK默认BD09LL坐标，百度定位SDK默认GCJ02坐标
		//mMapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		//mMapView.onPause();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "退出");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int item_id = item.getItemId();
		switch (item_id) {
		case 0:
			MainApplication.wfp="";
			MainApplication.mode = "";
            finish();
            startActivity(new Intent(CurrentLocus.this, MenuActivity.class));
			break;
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(new Intent(CurrentLocus.this, MenuActivity.class));
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (locationMode) {
			case NORMAL:
                button_location_mode.setText("跟随");
                locationMode = LocationMode.FOLLOWING;
				mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(locationMode, true, mCurrentMarker));
				//https://blog.csdn.net/niuba123456/article/details/81124739
				mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder(mBaiduMap.getMapStatus()).rotate(0).build()));
				mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder(mBaiduMap.getMapStatus()).overlook(0).build()));
				break;
			case COMPASS:
                button_location_mode.setText("标准");
                locationMode = LocationMode.NORMAL;
				mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(locationMode, true, mCurrentMarker));
				mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().rotate(0).build()));
				mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().overlook(0).build()));
				break;
			case FOLLOWING:
                button_location_mode.setText("罗盘");
                locationMode = LocationMode.COMPASS;
				mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(locationMode, true, mCurrentMarker));
				break;
			}
		}
	};

	public class MyLocationListenner extends BDAbstractLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null || mMapView == null) {
				return;
			}
			date = new Date();
			duration = date.getTime() - time_start.getTime();
			ltt = location.getLatitude();
			lgt = location.getLongitude();
			Gps gps = PositionUtil.gcj_To_Gps84(ltt, lgt);
			double ltt_gps = gps.getWgLat();
			double lgt_gps = gps.getWgLon();
			BigDecimal BD = BigDecimal.valueOf(location.getSpeed());
			speed = BD.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			BD = BigDecimal.valueOf(location.getAltitude());
			alt = BD.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			p1 = new LatLng(ltt, lgt);
			if (isFirstLoc) {
				p2 = p1;
				ltt1 = ltt;
				lgt1 = lgt;
				isFirstLoc = false;
				mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(15).build()));
				MapStatusUpdate MSU = MapStatusUpdateFactory.newLatLng(p1);
				mBaiduMap.animateMapStatus(MSU);
			}
			MyLocationData locationData = new MyLocationData.Builder().accuracy(location.getRadius()).direction(location.getDirection()).latitude(ltt).longitude(lgt).build();
			mBaiduMap.setMyLocationData(locationData);
			//distance = DistanceUtil.getDistance(p1, p2);
			BD = BigDecimal.valueOf(DistanceUtil.getDistance(p1, p2));
			distance = BD.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			ER = Math.round(location.getRadius());
			if (ER > 0 && ER < 100) {
				if (speed > speedmax)
					speedmax = speed;
				if (distance < 200) {
					List<LatLng> points = new ArrayList<LatLng>();
					points.add(p1);
					points.add(p2);
					OverlayOptions OOPolyline = new PolylineOptions().width(4).color(0xAA00FF00).points(points);
					mBaiduMap.addOverlay(OOPolyline);
				}
				ltt1 = ltt;
				lgt1 = lgt;
				p2 = p1;
				String sdistance = String.valueOf(distance);
				if (!sdistance.contains("E")) {
					lc += distance;
					distancesend = distance;
				}
				new Thread(t).start();
				String sltt = String.valueOf(ltt_gps);
				String slgt = String.valueOf(lgt_gps);
				if (!sltt.contains("E")  && !slgt.contains("E") && distance < 200) {
					RWXML.add(filename, dateformat.format(date), sltt, slgt, String.valueOf(alt), String.valueOf(speed), String.valueOf(lc), timeformatd.format(duration));
				}
				lci = (int) lc;
			}
			tv1.setText(location.getTime() + "\nLocType：" + location.getLocType() + "\n纬度：" + ltt + "\n经度：" + lgt + "\n误差半径：" + ER + "米" + "\n速度：" + speed + "米/秒\n高度：" + alt + "\n位移：" + distance + "米" + "\n卫星数目：" + location.getSatelliteNumber() + "\n地址：" + location.getAddrStr());
			tv2.setText("开始时间：" + timeformat.format(time_start) + "\n时长：" + timeformatd.format(duration) + "\n路程：" + lci + "米\n速度：" + speed + "米/秒\n最大速度：" + speedmax + "米/秒\n方向："	+ location.getDirection() + "\n上传：" + c);
			distance = 0;
		}
	}

	public void setMapMode(View view) {
		boolean checked = ((RadioButton) view).isChecked();
		switch (view.getId()) {
		case R.id.normal:
			if (checked)
				mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
			break;
		case R.id.satellite:
			if (checked)
				mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
			break;
		}
	}

	Thread t = new Thread() {
		@Override
		public void run() {
			String dateu = "";
			String timeu = "";
			try {
				dateu = URLEncoder.encode(dateformat2.format(date), "utf-8");
				timeu = URLEncoder.encode(timeformat.format(date), "utf-8");
			} catch (Exception e) {
				Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
			}
			Log.e(Thread.currentThread().getStackTrace()[2] + "", "误差半径：" + ER);
			if (ER > 0 && ER < 100) {
				String url = upload_server + "/add.php?date=" + dateu + "&time=" + timeu + "&longitude=" + lgt + "&latitude=" + ltt + "&speed=" + speed + "&distance=" + distancesend;
				Log.e(Thread.currentThread().getStackTrace()[2] + "", url);
				//RWXML.append(Environment.getExternalStorageDirectory().getPath() + "/LocusMap/BaiduMap.log", dateformat.format(date) + ": CurrentLocus: " + url);
				c = Utils.sendURLResponse(url);
			}
			distancesend = 0;
		}
	};

    void initNotification() {
        //设置后台定位
        //Android 8.0 及以上使用 NotificationUtils
        String title = "轨迹地图";
        String text = "正在定位";
        Notification.Builder builder;
        //if (Build.VERSION.SDK_INT >= 26) {
            NotificationUtils notificationUtils = new NotificationUtils(this);
            builder = notificationUtils.getAndroidChannelNotification(title, text);
//        } else {
//            builder = new Notification.Builder(this);
//            Intent intent = new Intent(this, CurrentLocus.class);
//            builder.setContentIntent(PendingIntent.getActivity(CurrentLocus.this, 0, intent, 0)) // 设置PendingIntent
//                    .setContentTitle(title) // 设置下拉列表里的标题
//                    .setSmallIcon(R.drawable.ic_launcher) // 设置状态栏内的小图标
//                    .setContentText(text) // 设置上下文内容
//                    .setWhen(System.currentTimeMillis());
//        }
        mNotification = builder.build();
        mNotification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
    }

}
